/**
 * 通用统计(单一日期 非区间 适用于：截止xx日期)
 */
import React from 'react'
import {Table, Form, DatePicker, Button} from 'antd'
import {exportFile, fetchPost} from '../../../../utils/request'
import {origin} from '../../../../utils/config'
import moment from 'moment'

const {RangePicker} = DatePicker
const FormItem = Form.Item

class SingleDateStats extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      downloadAllow: this.props.location.query.downloadAllow,
      buttonHidden: false,
      data: [],
      columns: [],
      params: {},
      queryKey: null,
      startDate: null,
      endDate: null,
      isShowDateSelect: this.props.isShowDateSelect,
      xLength: 2000,
      loading: false,
    }
  }

  componentDidMount() {
    let queryKey = null
    if (this.props.params != null && this.props.params.queryKey != null) {
      queryKey = this.props.params.queryKey
    } else {
      queryKey = this.props.queryKey
    }
    this.setState({
      queryKey: queryKey,
      endDate: this.getEndDate()
    }, () => {
      this.getData(this.state.endDate)
    })
  }

  componentWillReceiveProps(props) {
    let queryKey = null
    if (props.params != null && props.params.queryKey != null) {
      queryKey = props.params.queryKey
    } else {
      queryKey = props.queryKey
    }
    if(this.state.queryKey != queryKey){
      this.setState({
        queryKey: queryKey
      }, () => {
        this.getData(this.state.endDate)
      })
    }
  }

  getData(endDate) {
    this.setState({
      loading: true
    })
    let param = {
      ...this.state.params,
      queryKey: this.state.queryKey,
      endDate: endDate
    }
    fetchPost(`/bizStats/general/query`, param).then(json => {
      if (json && json.data != null && JSON.stringify(json.data) != '{}' && json.code === 0) {
        let queryKey = this.state.queryKey
        let keyList = json.data[`${queryKey}KeyList`]
        let data = json.data[queryKey]
        let columns = []
        let xLengthTmp = 0
        if (keyList != null && keyList.length > 0) {
          keyList.map(item => {
            columns.push({
              title: item,
              dataIndex: item,
              key: item
            })
            xLengthTmp += item.length
          })

          this.setState({
            data: data,
            columns: columns,
            xLength: xLengthTmp * 6.8, //按标题计算宽度
            loading: false
          })
        } else {
          this.setState({
            data: [],
            columns: [],
            loading: false
          })
        }

      } else {
        this.setState({
          data: [],
          columns: [],
          loading: false
        })
      }
    })
  }

  changeParams(params) {
    this.setState({
      params,
    }, () => {
      this.getData()
    })
  }

  handelDateChange = (date, dateString) => {
    this.setState({
      endDate: dateString
    }, () => {
      this.getData(this.state.endDate)
    })
  }

  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, fieldsValue) => {
      const rangeValue = fieldsValue['datePicker']
      let endDate = rangeValue
      this.setState({
        endDate: endDate.format('YYYY-MM-DD')
      })
      this.getData(endDate.format('YYYY-MM-DD'))
    })
  }

  getEndDate() {
    let date = new Date()
    let separator = '-'
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let strDate = date.getDate()
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate
    }
    return year + separator + month + separator + strDate
  }

  // 导出excel
  handelExport = () => {
    this.setState({
      buttonHidden: true
    })
    const {queryKey, endDate} = this.state
    let copyParams = {
      queryKey, endDate
    }
    exportFile('/bizStats/general/export', `data-${moment().format('YYYY-MM-DD')}.xls`, copyParams).then(json => {
      this.setState({
        buttonHidden: false
      })
    })
  }

  render() {
    const dateFormat = 'YYYY-MM-DD'
    const rangeConfig = {
      rules: [{type: 'object', required: true, message: 'Please select Time!'}],
      initialValue: this.state.endDate != null ? moment(this.state.endDate, dateFormat) : moment()
    }
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
    }

    const itemLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 16, offset: 8},
      }
    }
    const {getFieldDecorator} = this.props.form
    return (
      <div>
        <div style={{width: 600}}>

          {this.state.isShowDateSelect == '0' ? null :
            <Form layout="inline" onSubmit={this.handleSubmit}>
              <FormItem {...formItemLayout} label="Date">
                {getFieldDecorator('datePicker', rangeConfig)(
                  <DatePicker onChange={this.handelDateChange}/>
                )}
              </FormItem>

              <FormItem {...itemLayout} >
                <Button type="primary" htmlType="submit">Search</Button>
              </FormItem>

              {this.state.downloadAllow ?
                <FormItem {...itemLayout} >
                  <Button type="primary" disabled={this.state.buttonHidden} onClick={this.handelExport}>Export</Button>
                </FormItem> : null
              }

            </Form>}

        </div>
        <div className="mt20">
          <Table
            pagination={false}
            bordered
            scroll={{x: this.state.xLength}}
            size='small'
            dataSource={this.state.data}
            columns={this.state.columns}
            title={() => 'Result'}
            loading={this.state.loading}
          />
        </div>
      </div>
    )
  }
}

const SingleDateStats2 = Form.create()(SingleDateStats)

export default SingleDateStats2

